package com.hyjiacan.tools.apps.dbm.utils

import com.hyjiacan.tools.apps.dbm.models.ConnectionModel
import com.hyjiacan.tools.utils.Json
import com.hyjiacan.tools.utils.Rsa
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

object Misc {
    @Throws(Exception::class)
    fun decodeOption(conOpts: String?): ConnectionModel {
        val conOptsStr = Rsa.decrypt(conOpts)
        return Json.parse(conOptsStr, ConnectionModel::class.java)
    }

    fun getTmpPath(): String {
        val root = System.getProperty("user.dir")
        val tempRoot = Paths.get(root, "tmp")
        if (!Files.exists(tempRoot)) {
            Files.createDirectory(tempRoot)
        }
        return tempRoot.toAbsolutePath().toString()
    }

    fun deleteDirectoryRecursively(directoryPath: String, deleteDir: Boolean = true) {
        val dirPath: Path = Paths.get(directoryPath)

        // 检查路径是否存在且是一个有效的目录
        if (Files.exists(dirPath) && Files.isDirectory(dirPath)) {
            try {
                // 遍历目录下的所有文件和子目录，并递归删除
                Files.list(dirPath).forEach { path ->
                    try {
                        if (Files.isDirectory(path)) {
                            // 递归调用，删除子目录
                            deleteDirectoryRecursively(path.toString())
                        }
                        // 删除文件或空目录
                        Files.delete(path)
                        println("已删除: $path")
                    } catch (e: IOException) {
                        println("无法删除: $path，错误: ${e.message}")
                    }
                }
                if (deleteDir) {
                    // 删除空目录
                    Files.delete(dirPath)
                    println("已删除目录: $dirPath")
                }
            } catch (e: IOException) {
                println("无法访问目录 $directoryPath: ${e.message}")
            }
        } else {
            println("目录不存在或不是有效的目录: $directoryPath")
        }
    }

    fun zipFile(input: File, output: String) {
        val outputStream = ZipOutputStream(FileOutputStream(output))

        val inputStream = input.inputStream()
        outputStream.putNextEntry(ZipEntry(input.getName()))

        while (inputStream.available() > 0) {
            val buffer = ByteArray(1024 * 1024)
            val len = inputStream.read(buffer)
            outputStream.write(buffer, 0, len)
            outputStream.flush()
        }
        outputStream.closeEntry()

        inputStream.close()
        outputStream.close()
    }

    // 计算包含 Unicode 字符的字符串长度
    @OptIn(ExperimentalStdlibApi::class)
    fun calculateUnicodeLength(value: String): Int {
        return value.fold(0) { acc, char ->
            acc + if (
                char.isHighSurrogate() || char.isLowSurrogate()
            ) 0 else (
                    if (Character.UnicodeScript.of(char.code) == Character.UnicodeScript.HAN) 2 else 1
                    )
        }
    }
}